package io.gitee.zhangbinhub.acp.boot.tools

import io.gitee.zhangbinhub.acp.core.common.CommonTools
import io.gitee.zhangbinhub.acp.core.common.NetTools
import org.noear.solon.core.handle.Context

/**
 * IP 相关工具类
 */
object IpTools {
    /**
     * 获取WEB应用访问服务器的IP
     *
     * @return 服务器IP
     */
    @JvmStatic
    fun getServerIps(): List<String> = NetTools.getServerIps()

    /**
     * 获取WEB应用访问服务器的IP
     *
     * @return 服务器IP
     */
    @JvmStatic
    fun getServerIp(): String? = NetTools.getServerIp()

    /**
     * 获取WEB应用访问服务器的物理地址
     *
     * @return 服务器物理地址
     */
    @JvmStatic
    fun getMacAddress(): String = NetTools.getMacAddress()

    /**
     * 获取远程客户端IP
     *
     * @param context 请求上下文
     * @return IP
     */
    @JvmStatic
    fun getRemoteIP(context: Context): String? {
        var ipAddress: String? = context.header("X-Forwarded-For")
        if (CommonTools.isNullStr(ipAddress) || "unknown".equals(ipAddress!!, ignoreCase = true)) {
            ipAddress = context.header("Citrix-Client-IP")
        }
        if (CommonTools.isNullStr(ipAddress) || "unknown".equals(ipAddress!!, ignoreCase = true)) {
            ipAddress = context.header("Proxy-Client-IP")
        }
        if (CommonTools.isNullStr(ipAddress) || "unknown".equals(ipAddress!!, ignoreCase = true)) {
            ipAddress = context.header("WL-Proxy-Client-IP")
        }
        if (CommonTools.isNullStr(ipAddress) || "unknown".equals(ipAddress!!, ignoreCase = true)) {
            ipAddress = getRemoteRealIP(context)
        }
        return NetTools.formatIpAddress(ipAddress)
    }

    /**
     * 获取远程客户端真实底层IP
     *
     * @param context 请求上下文
     * @return IP
     */
    private fun getRemoteRealIP(context: Context): String? = context.remoteIp()
}
